import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Drawer, Message, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import LineTimeForm from './components/LineTimeForm';
import { column, toSelectDataSource, ENUMS } from './stores/definitions';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import { useHistory } from 'react-router';

const TAB_ITEMS = [
  { key: '2', label: t`专线线路` },
  { key: '3', label: t`巴士线路` },
];

function parseRegion(s, type) {
  if (!s?.length) return {};
  // 专线搜索条件只有两级 巴士有三级 需区分处理
  return { main: s[0]?.value, minor: s[Number(type) - 1]?.id };
}

function Index() {
  const { lineTimeStore: store } = useStore();
  const [modal, setModal] = useState({
    show: null,
    record: null,
  });
  const [dup, setDup] = useState([]);
  const [companyData, setCompanyData] = useState([]);
  const [stationType, setStationType] = useState('2');

  const history = useHistory();

  useEffect(() => {
    (async () => {
      const res = await store.getCompany({ search: { isOperating: true }, pg: { page: 0, size: 10 } });
      setCompanyData(res);
    })();
  }, []);

  const handleSearch = (params) => {
    const { start: _, end: __, ...searchArgs } = params.values;
    const { start, end } = params?.valueObjects;
    const { main: fromCityId, minor: startStations } = parseRegion(start?.selectedPath, store._lineStatus);
    const { main: toCityId, minor: endStations } = parseRegion(end?.selectedPath, store._lineStatus);

    store.search = {
      fromCityId,
      onStationId: startStations,
      toCityId,
      offStationId: endStations,
      ...searchArgs,
    };
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    setModal({ show: 'add', record: null });
  };

  // 点击打开编辑
  const handleOpenEdit = (price) => {
    setModal({ show: 'edit', record: price });
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal({ show: null, record: null });
  };

  // 变更数据提交
  const handleUpdate = async (price) => {
    if (!_.isEmpty(price)) {
      try {
        await store.update(toJS(price));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  // 新增订单数据提交
  const handleCreate = async (price) => {
    // const exists = await store.exitingLines(price);
    // if (exists.length > 0 && exists[0].startMain) {
    //   setDup(exists);
    //   return;
    // }

    if (!_.isEmpty(price)) {
      try {
        await store.create(toJS(price));
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  const handleDelete = (price) => {
    Dialog.confirm({
      content: t`确认删除该线路吗？`,
      onOk: async () => {
        try {
          await store.remove(toJS(price));
          Message.success({ content: t`删除成功` });
        } catch (e) {
          Message.error({ content: t`删除失败`, duration: 7000 });
          throw e;
        }
      },
    });
  };

  const handleOpenStation = (record) => {
    history.push(`/price/lineTime/${record.id}`);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        className="action-panel"
        onSearch={handleSearch}
        actions={[
          {
            name: 'btn-addPrice',
            title: t`添加线路`,
            type: 'primary',
            onClick: () => handleOpenAdd(),
          },
        ]}
        searchItems={[
          {
            name: 'start',
            type: stationType,
            props: {
              placeholder: store._lineStatus == 3 ? t`请选择巴士上车站点` : t`请选择专线上车站点`,
              style: { width: 200 },
              direction: '0',
            },
          },
          {
            name: 'end',
            type: stationType,
            props: {
              placeholder: store._lineStatus == 3 ? t`请选择巴士下车站点` : t`请选择专线下车站点`,
              style: { width: 200 },
              direction: '0',
            },
          },
          {
            name: 'companyIds',
            type: 'select',
            props: {
              placeholder: t`公司名称`,
              style: { width: 300 },
              dataSource: companyData,
              mode: 'multiple',
            },
          },
          {
            name: 'enable',
            type: 'select',
            props: {
              placeholder: t`是否启用`,
              dataSource: toSelectDataSource(ENUMS._enable),
            },
          },
        ]}
      />
      <div className="content">
        <Tab
          defaultActiveKey={store._lineStatus}
          accessKey={store._lineStatus}
          onChange={(v) => {
            store.lineStatus = v;
            if (v == '3') {
              setStationType('bus-station');
            } else if (v == '2') {
              setStationType('sc-station');
            }
          }}
        >
          {TAB_ITEMS.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
        </Tab>
        <TauTable
          primaryKey="itemId"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 77, cell: (v, i) => store.idx(i) },
            column('companyInfo', { width: 240 }),
            column('fromCityName', {}),
            column('onStationName', {}),
            column('toCityName', {}),
            column('offStationName', {}),
            column('enable', {}),
            column('duration', { width: 120 }),
            column('mileage', { width: 120 }),
            {
              title: t`操作`,
              dataIndex: 'id',
              width: 200,
              cell: (_, __, price) => {
                const funcMenu = [
                  {
                    title: '编辑',
                    onClick: () => handleOpenEdit(price),
                  },
                  {
                    title: '删除',
                    onClick: () => handleDelete(price),
                    color: 'red',
                  },
                  {
                    title: '途径站点',
                    onClick: () => handleOpenStation(price),
                  },
                ];
                return (
                  <>
                    <MoreFuncDropDown
                      dropdownItems={funcMenu}
                      maxShow={1}
                      key={price.id}
                    />
                  </>
                );
              },
            },

          ]}
        />
      </div>
      <Drawer
        visible={modal.show === 'add' || modal.show === 'edit'}
        title={modal.show === 'add' ? t`添加线路时长` : t`修改线路时长`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, toClose: `toClose$${Date.now()}` })}
        width="90%"
      >
        <LineTimeForm
          priceId={modal.record?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal.show === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Dialog
        v2
        title={t`存在重复的线路`}
        centered
        width="50%"
        height="70vh"
        onOk={() => setDup([])}
        onClose={() => setDup([])}
        visible={dup.length}
        footerActions={['ok']}
      >
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
          {/* <span>{t`重复的线路:`}</span> */}
          {dup.map((v) => <span>{`${v.startMainText}-${v.startMinorText} ---> ${v.endMainText}-${v.endMinorText}`}</span>)}
        </div>
      </Dialog>
    </TauPage>
  );
}

export default observer(Index);
